<?php
namespace App\Admin\Controllers;

// use Encore\Admin\Auth\Database\Administrator;
// use Encore\Admin\Auth\Database\Role;
use Illuminate\Http\Request;
use DB;
use App\Models\Casual_xc_res;
use App\Models\Casual_xc_record;
use App\Models\Casual_xc_ques_type;
use  App\Admin\Controllers\Common\ReportBase;
class Xc_reportController extends ReportBase {
	public function __construct() {
		$term = DB::table("terms")->orderBy("id",'desc')->first();
		parent::__construct($term->year,$term->season);
	}
    public  function navigation_view(Request $request) {
		// 用于控制PC,mobile的参数
		$date = isset($request['date'])?$request['date']:date('Y-m-d');
		$is_mobile = isset($request['is_mobile'])?$request['is_mobile']:$this->is_mobile();
		$chartType0 = isset($request['chart_type0'])?$request['chart_type0']:0;
		$chartType1 = isset($request['chart_type1'])?$request['chart_type1']:0;
		$chartType2 = isset($request['chart_type2'])?$request['chart_type2']:0;

		$data = $this->getData($date);
		if($is_mobile === true){
			return view('admin.xunchang.mobile.xc_report_view',[
				'date' => $date,
				'Data' => $data
			]);
		}else{
			return view('admin.xunchang.xc_report_view',[
				'date'=>$date,
				'is_mobile' => $is_mobile,
				'chartType' => [$chartType0,$chartType1,$chartType2],
				'Data' => $data
			]);
		}
    }
	private function getData($date) {
		$datetime_s = $date." 00:00:00";
		$datetime_e = $date." 23:59:59";
		$lastweek_s = date("Y-m-d H:i:s",strtotime($datetime_s) - 7*24*3600);
		$lastweek_e = date("Y-m-d H:i:s",strtotime($datetime_s) - 6*24*3600 - 1);
		$campuses = DB::table("campuses")->get(['id','name']);
		$campuses = json_decode(json_encode($campuses),true);
		$data = [];
		$find_total = 0;
		$solve_total = 0;
		$find_last_total = Casual_xc_record::where(["status"=>"0"])->whereBetween('created_at',[$lastweek_s,$lastweek_e])
			->count();
		$solve_last_total = Casual_xc_record::where(['is_handled'=>'1','status'=>"0"])
			->whereBetween('created_at',[$lastweek_s,$lastweek_e])
			->count();
		foreach($campuses as $v){
			$find = Casual_xc_record::where(['compus'=>$v['id'],"status"=>"0"])
				->whereBetween('created_at',[$datetime_s,$datetime_e])
				->count();
			$solve = Casual_xc_record::where([
				'compus'=>$v['id'],
				"status"=>"0",
				'is_handled'=>'1',
				])->whereBetween('created_at',[$datetime_s,$datetime_e])
				->count();
			$rate = $find?round(($solve/$find*100),2):"--";
			$problems = DB::table("casual_xc_records as records")
				->leftJoin('casual_xc_ques_types as t','records.ques_type_id','=','t.id')
				->leftJoin('admin_users as admin','records.handle_user_id','=','admin.id')
				->leftJoin('departments as depart','records.dep_id','=','depart.id')
				->where("records.compus",'=',$v['id'])
				->where("records.is_changqi",'=',"0")
				->where("records.status",'=',"0")
				->whereBetween('records.created_at',[$datetime_s,$datetime_e])
				->get(['t.type_name as problem_type','admin.username as admin_name','depart.name as depart_name','records.*']);
			$problems = json_decode(json_encode($problems),true);
			foreach($problems as &$p){
				$p['remark'] = mb_strlen($p['ques_desc']) <= 17 ? $p['ques_desc'] : mb_substr($p['ques_desc'],0,17)."...";
				$p['campus'] = $v['name'];
				$p['params'] = json_encode($p);
			}
			$long_problems = DB::table("casual_xc_records as records")
				->leftJoin('casual_xc_ques_types as t','records.ques_type_id','=','t.id')
				->leftJoin('admin_users as admin','records.handle_user_id','=','admin.id')
				->leftJoin('departments as depart','records.dep_id','=','depart.id')
				->where([
					["records.compus",'=',$v['id']],
					["records.is_changqi",'=',"1"],
					["records.status",'=',"0"]
				])->where(function($query){
					$query->where("records.end_date","<",date("Y-m-d")." 00:00:00")
					->orWhere(function($query){
						$Wednesday = date("Y-m-d",strtotime("Sunday -4 day"))." 00:00:00";
						$Tuesday = date("Y-m-d",strtotime("Sunday +2 day"))." 23:59:59";
						$query->where('records.end_date',">=",$Wednesday)
						->where('records.end_date',"<=",$Tuesday);
					})->orWhere(function($query){
						$query->where('records.created_at',">=",date("Y-m-d")." 00:00:00")
						->where('records.created_at',"<=",date("Y-m-d")." 23:59:59");
					});
				})->get([
					't.type_name as problem_type',
					'admin.username as admin_name',
					'depart.name as depart_name','records.*'
				]);
			$long_problems = json_decode(json_encode($long_problems),true);
			foreach($long_problems as &$lp){
				$lp['remark'] = mb_strlen($lp['ques_desc']) <= 17 ? $lp['ques_desc'] : mb_substr($lp['ques_desc'],0,17)."...";
				$lp['campus'] = $v['name'];
				$lp['params'] = json_encode($lp);
			}
			$data['campuses'][] = [
				'campus' => $v['name'],
				'campus_id' => $v['id'],
				'find' => $find,
				'solve' => $solve,
				'rate' => $rate,
				'problems' => $problems,
				"long_problems" => $long_problems
			];
			$find_total += $find;
			$solve_total += $solve;
		}
		$data['total'] = [
			'find' => $find_total,
			'solve' => $solve_total,
			'find_last' => $find_last_total,
			'solve_last' => $solve_last_total,
		];
		$data['total']['rate'] = $data['total']['find']?round(($data['total']['solve']/$data['total']['find']*100),2):"--";
		$data['total']['rate_last'] = $find_last_total?round(($solve_last_total/$find_last_total*100),2):"--";
		return $data;
	}

	/**
	 * [获取图表数据]
	 */
	public function getChartData(Request $request) {
		try {
			$data = [];
			$campuses = DB::table("campuses")->get(['id','name']);
			$campuses = json_decode(json_encode($campuses),true);
			for($i=6;$i>=0;$i--){
				$week = date("w",(strtotime($request['date']." 00:00:00")-$i*24*3600));
				switch ($week) {
					case 0:
						$data['x_data'][] = "周日";
						break;
					case 1:
						$data['x_data'][] = "周一";
						break;
					case 2:
						$data['x_data'][] = "周二";
						break;
					case 3:
						$data['x_data'][] = "周三";
						break;
					case 4:
						$data['x_data'][] = "周四";
						break;
					case 5:
						$data['x_data'][] = "周五";
						break;
					case 6:
						$data['x_data'][] = "周六";
						break;
				}
				$time_s = date("Y-m-d",strtotime($request['date'])-$i*24*3600)." 00:00:00";
				$time_e = date("Y-m-d",strtotime($request['date'])-$i*24*3600)." 23:59:59";
				foreach($campuses as $ke => $ca) {
					$day_total = DB::table('casual_xc_records')
						->where("status","=","0")
						->where('compus','=',$ca['id'])
						->whereBetween('created_at',[$time_s,$time_e])->count();
					$data['series_0'][$ke]['data'][] = $day_total;
				}
			}
			$line_color_arr = ["#417293","#67C23A","#48bacc"];
			foreach($campuses as $k => $c) {
				$total = $data['series_0'][$k]['data'][6];
				$data['series_0'][$k]['name'] = $c['name']."总计：".$total;
				$data['series_0'][$k]['type'] = "line";
				$data['series_0'][$k]['color'] = $line_color_arr[$k];
				$data['legend_0'][] = $c['name']."总计：".$total;
				// pie
				$total_count = DB::table("casual_xc_records")
					->where('compus','=',$c['id'])
					->where("status","=","0")
					->whereBetween('created_at',[
						$request['date']." 00:00:00",
						$request['date']." 23:59:59"
					])->count();
				$series_1 = DB::table('casual_xc_records as r')
					->leftJoin("casual_xc_ques_types as t",'r.ques_type_id','=','t.id')
					->where('r.compus','=',$c['id'])
					->where("r.status","=","0")
					->whereBetween('r.created_at',[
						$request['date']." 00:00:00",
						$request['date']." 23:59:59"
					])->groupBy("r.ques_type_id")->groupBy("r.is_handled")
					->orderBy("r.is_handled","asc")
					->get([
						DB::raw('count(1) as value'),
						't.type_name as name','r.is_handled'
					]);
				$color_1 = $this->mkColor($series_1);
				$series_1 = $this->mkPieFormat($series_1,$total_count);


				$series_2 = DB::table('casual_xc_records as r')
					->leftJoin("departments as d",'r.dep_id','=','d.id')
					->where('r.compus','=',$c['id'])
					->where("r.status","=","0")
					->whereBetween('r.created_at',[
						$request['date']." 00:00:00",
						$request['date']." 23:59:59"
					])->groupBy("r.dep_id")->groupBy("r.is_handled")
					->orderBy("r.is_handled","asc")
					->get([
						DB::raw('count(1) as value'),
						'd.name','r.is_handled'
					]);
				$color_2 = $this->mkColor($series_2);
				$series_2 = $this->mkPieFormat($series_2,$total_count);
				if($c['id'] == 1){
					$data['series_1'] = $series_1;
					$data['series_2'] = $series_2;
					$data['color_1'] = $color_1;
					$data['color_2'] = $color_2;
				}elseif($c['id'] == 2){
					$data['series_3'] = $series_1;
					$data['series_4'] = $series_2;
					$data['color_3'] = $color_1;
					$data['color_4'] = $color_2;
				}else{
					$data['series_5'] = $series_1;
					$data['series_6'] = $series_2;
					$data['color_5'] = $color_1;
					$data['color_6'] = $color_2;
				}
			}
			return ['code'=>1,'msg'=>'ok','data'=>$data];
		} catch (\Exception $e) {
			return ['code'=>0,'msg'=>'获取数据失败：'.$e->getMessage(),"data"=>""];
		}
	}

	private function mkPieFormat($data,$total_count) {
		$data = json_decode(json_encode($data),true);
		foreach($data as &$value){
			if($value['is_handled'] == 1){
				$value['name'] .= "\n（已处理）\n";
			}else{
				$value['name'] .= "\n（未处理）\n";
			}
			$value['name'] .= $value['value']."个";
			$value['name'] .= '，'.(round($value['value'] / $total_count,4)*100)."%";
			unset($value['is_handled']);
		}
		return $data;
	}

	private function mkColor($data) {
		$data = json_decode(json_encode($data),true);
		$cold = ["#417293","#3f9cbc","#48bacc","5bd3bc","#97d371"];
		$cold_index=0;
		$warm = ["#e84f40","#f77846","#f49351","#f7be7f","#e6e0d2"];
		$warm_index=0;
		$color = [];
		foreach($data as &$value){
			if($value['is_handled'] == 1){
				$cold_index = $cold_index > 4 ? 0 : $cold_index;
				$color[] = $cold[$cold_index];
				$cold_index++;
			}else{
				$warm_index = $warm_index > 4 ? 0 : $warm_index;
				$color[] = $warm[$warm_index];
				$warm_index++;
			}
		}
		return $color;
	}

	/**
	 * [编辑备注]
	 */
	public function editMark(Request $request) {
		DB::beginTransaction();
		try {
			DB::table("casual_xc_records")
				->where('id','=',$request['id'])
				->update(['mark'=>$request['mark']]);
			DB::commit();
			return ['code'=>1,'msg'=>'编辑成功'];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'编辑失败，请稍后...'.$e->getMessage()];
		}
	}

    // public function get_xc_data(Request $request) {
    //     $date = isset($request['date'])?$request['date']:date('Y-m-d');
    //     $start_date = $date." 00:00:00";
    //     $end_date = $date." 23:59:59";
    //     //查询出对应校区营业前、中后、偶发的问题总数及已处理总数
    //     //七彩营业前发现问题总数
    //     $qicai['before_total'] = Casual_xc_record::where(['compus'=>'1','time_type'=>'1','xc_type'=>'2','status'=>'0'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //七彩营业前已处理问题总数
    //     $qicai['before_handled'] = Casual_xc_record::where(['compus'=>'1','time_type'=>'1','xc_type'=>'2','status'=>'0','is_handled'=>'1'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //七彩中后发现问题总数
    //     $qicai['on_total'] = Casual_xc_record::where(['compus'=>'1','time_type'=>'2','xc_type'=>'2','status'=>'0'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //七彩中后已处理问题总数
    //     $qicai['on_handled'] = Casual_xc_record::where(['compus'=>'1','time_type'=>'2','xc_type'=>'2','status'=>'0','is_handled'=>'1'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //七彩偶发发现问题总数
    //     $qicai['of_total'] = Casual_xc_record::where(['compus'=>'1','xc_type'=>'1','status'=>'0'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //七彩偶发已处理问题总数
    //     $qicai['of_handled'] = Casual_xc_record::where(['compus'=>'1','xc_type'=>'1','status'=>'0','is_handled'=>'1'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //C86营业前发现问题总数
    //     $C86['before_total'] = Casual_xc_record::where(['compus'=>'2','time_type'=>'1','xc_type'=>'2','status'=>'0'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //C86营业前已处理问题总数
    //     $C86['before_handled'] = Casual_xc_record::where(['compus'=>'2','time_type'=>'1','xc_type'=>'2','status'=>'0','is_handled'=>'1'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //C86中后发现问题总数
    //     $C86['on_total'] = Casual_xc_record::where(['compus'=>'2','time_type'=>'2','xc_type'=>'2','status'=>'0'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //C86中后已处理问题总数
    //     $C86['on_handled'] = Casual_xc_record::where(['compus'=>'2','time_type'=>'2','xc_type'=>'2','status'=>'0','is_handled'=>'1'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //C86偶发发现问题总数
    //     $C86['of_total'] = Casual_xc_record::where(['compus'=>'2','xc_type'=>'2','status'=>'0'])->whereBetween('created_at',[$start_date,$end_date])->count();
    //     //C86偶发已处理问题总数
    //     $C86['of_handled'] = Casual_xc_record::where(['compus'=>'2','xc_type'=>'1','status'=>'0','is_handled'=>'1'])->whereBetween('created_at',[$start_date,$end_date])->count();
	//
    //     /*
    //     查出所选日期下未处理记录详情
    //     */
    //     $ques_list  = DB::table('casual_xc_records')->leftJoin('full_xc_ques',function($join){
    //             $join->on('casual_xc_records.ques_id','=','full_xc_ques.id');
    //         })->leftJoin('casual_xc_ques_types',function($join){
    //             $join->on('casual_xc_ques_types.id','=','casual_xc_records.ques_type_id');
    //         })->where(['is_handled'=>'0','status'=>'0'])->whereBetween('created_at',[$start_date,$end_date])->get(['casual_xc_records.id','casual_xc_records.compus','casual_xc_records.time_type','casual_xc_records.xc_type','casual_xc_records.xc_res_id','full_xc_ques.ques_title','full_xc_ques.ques_desc','casual_xc_ques_types.type_name','casual_xc_records.is_changqi','casual_xc_records.end_date','casual_xc_records.ques_desc as xc_desc','casual_xc_records.ques_img','casual_xc_records.xc_user'])->toArray();
    //     foreach ($ques_list as $key => $value) {
    //         if (!is_null($ques_list[$key]->xc_res_id)) {
    //             $ques_list[$key]->xc_res_id = $this->get_res_full_name($ques_list[$key]->xc_res_id);
    //         }
	//
    //         if($ques_list[$key]->compus == '1')
    //         {
    //             $ques_list[$key]->compus = "七彩校区";
    //         }
    //         if($ques_list[$key]->compus == '2')
    //         {
    //             $ques_list[$key]->compus = "C86校区";
    //         }
	//
    //         if($ques_list[$key]->time_type == '1')
    //         {
    //             $ques_list[$key]->time_type = "营业前";
    //         }
    //         if($ques_list[$key]->time_type == '2')
    //         {
    //             $ques_list[$key]->time_type = "中后";
    //         }
	//
	//
    //         if($ques_list[$key]->xc_type == '1')
    //         {
    //             $ques_list[$key]->xc_type = "偶发巡场";
    //         }
    //         if($ques_list[$key]->xc_type == '2')
    //         {
    //             $ques_list[$key]->xc_type = "全场巡场";
    //         }
	//
    //         if(!is_null($ques_list[$key]->ques_img))
    //         {
    //             $ques_list[$key]->ques_img = explode(";", $ques_list[$key]->ques_img);
    //         }
    //     }
    //     //dd($ques_list);
    //     //按问题分类分组统计
    //     $ques_type_group = DB::table('casual_xc_records')->leftJoin('casual_xc_ques_types',function($join){
    //             $join->on('casual_xc_records.ques_type_id','=','casual_xc_ques_types.id');
    //         })->where('casual_xc_records.status','0')->whereBetween('created_at',[$start_date,$end_date])->groupBy('casual_xc_records.ques_type_id')->get([DB::raw('count(casual_xc_records.ques_type_id) as value'),'casual_xc_ques_types.type_name as name'])->toArray();
    //     //dd($ques_type_group);
    //     //按校区分组统计
    //     $compus = DB::table('casual_xc_records')->select(DB::raw('count(compus) as value'),'compus as name')->where('status','0')->whereBetween('created_at',[$start_date,$end_date])->groupBy('compus')->get()->toArray();
    //     //dd($compus);
    //     foreach ($compus as $ck => $cv) {
    //         if ($compus[$ck]->name=='1') {
    //             $compus[$ck]->name="七彩校区";
    //         }
    //         if ($compus[$ck]->name=='2') {
    //             $compus[$ck]->name="C86校区";
    //         }
    //     }
	//
    //     //dd($compus);
    //     //按部门分组统计
    //     $dep = DB::table('casual_xc_records')->leftJoin('departments',function($join){
    //             $join->on('casual_xc_records.dep_id','=','departments.id');
    //         })->where('casual_xc_records.status','0')->whereBetween('created_at',[$start_date,$end_date])->groupBy('casual_xc_records.dep_id')->get([DB::raw('count(casual_xc_records.dep_id) as value'),'departments.name'])->toArray();
	//
    //     //按处理状态分组统计
    //     $handle = DB::table('casual_xc_records')->select(DB::raw('count(compus) as value'),'is_handled as name')->whereBetween('created_at',[$start_date,$end_date])->where('status','0')->groupBy('is_handled')->get()->toArray();
	//
    //     foreach ($handle as $hk => $hv) {
    //         if ($handle[$hk]->name=='0') {
    //             $handle[$hk]->name="未处理";
    //         }
    //         if ($handle[$hk]->name=='1') {
    //             $handle[$hk]->name="已处理";
    //         }
    //     }
    //     //dd($handle);
    //     return array('start_date'=>$start_date,'qicai'=>$qicai,'C86'=>$C86,'ques_list'=>$ques_list,'status'=>'1','message'=>'成功！','char_data'=>array('ques_type_group'=>$ques_type_group,'compus'=>$compus,'dep'=>$dep,'handle'=>$handle));
    // }
	//
	//
    // public function get_res_full_name($res_id) {
    //     $res_full_name = '';
    //     //上一级点位ID
    //     $parent_res1 = Casual_xc_res::where('id',$res_id)->pluck('res_name','pid')->toArray();
    //     //dd($parent_res1);
    //     //上2级点位ID
    //     foreach ($parent_res1 as $key1 => $value1) {
    //         $parent_res2 = Casual_xc_res::where('id',$key1)->pluck('res_name','pid')->toArray();
    //         //dd($parent_res2);
    //         if ($key1!=0) {
    //             foreach ($parent_res2 as $key2 => $value2) {
    //                 $parent_res3 = Casual_xc_res::where('id',$key2)->pluck('res_name','pid')->toArray();
    //                 //dd($parent_res3);
    //                 //如果没到顶，则接着找出上3级点位id
    //                 if ($key2!=0) {
    //                     foreach ($parent_res3 as $key3 => $value3) {
    //                         $parent_res4 = Casual_xc_res::where('id',$key3)->pluck('res_name','pid')->toArray();
    //                         //dd($parent_res4);
    //                         if ($key3!=0) {
    //                             foreach ($parent_res4 as $key4 => $value4) {
    //                                 $res_full_name .= $value4.">".$value3.">".$value2.">".$value1;
    //                                 //dd($res_full_name);
    //                             }
    //                         }
    //                         else{
    //                             $res_full_name .= $value3.">".$value2.">".$value1;
    //                         }
    //                     }
    //                 }else{
    //                     //到顶
    //                     $res_full_name .= $value2.">".$value1;
    //                 }
    //             }
    //         }else{
    //             $res_full_name .= $value1;
    //         }
    //     }
    //     return $res_full_name;
    // }
}
